<template>
  <el-dialog modal-class="email-rule-modal" model-value="true" width="600px" title="规则设置">
    <div class="email-rule-dialog">
      <div class="flex">
        <span style="line-height: 32px;">邮箱账户：</span>
        <el-select
          v-model="currentAccout"
          class="m-2"
          placeholder="Select"
          size="small"
          style="width: 358px"
        >
          <el-option
            v-for="item in accountList"
            :key="item.id"
            :label="item.account"
            :value="item.account"
          />
        </el-select>
      </div>
      <div class="email-rule-wrap">
        <div class="email-rule-table-head">
          <div class="flex-row">
            <div class="flex-row-item">
              <span class="font12">状态</span>
            </div>
            <div class="flex-row-item">
              <span class="font12">条件</span>
            </div>
            <div class="flex-row-item">
              <span class="font12">操作</span>
            </div>
          </div>
        </div>
        <div v-for="(i, index) in emailRuleList" :key="index">
          <div class="email-rule-table-item">
            <div @click="handleChangeStatus(i)" class="flex-row hand" :class="currentRuleId === i.id ? 'active' : ''">
              <div class="flex-row-item">
                <el-checkbox @change="changeEmailStatus(i)" :false-label="1" :true-label="0" v-model="i.status" size="large" />
              </div>
              <div class="flex-row-item">
                <span class="font12">{{ formatCondition(i) }}</span>
              </div>
              <div class="flex-row-item">
                <span class="font12">{{ formatOperation(i)}}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="footer-wrap">
        <el-button-group>
          <el-button @click="addEmailItem" size="small">
            <i class="iconfont icon-plus" />
          </el-button>
          <el-button @click="deleteEmailItem" :disabled="!currentRuleId" size="small">
            <i class="iconfont icon-minus" />
          </el-button>
        </el-button-group>
        <el-button @click="ediRule()" size="small" :disabled="!currentRuleId">
          编辑
        </el-button>
      </div>
    </div>
    <el-dialog title="来信分类规则" modal-class="email-item-rule-modal" :show-close="false" v-model="ruleItemDialogVisible" width="550px">
      <p class="bold tips mb30 font16">收到新邮件时，规则如下</p>
      <p class="bold tips mb8 font14">当符合下列所有条件：</p>
      <div class="">
        <div class="flex-row mb10 rule-item-wrap" v-for="(item, index) in ruleList" :key="index">
          <el-select
            v-model="item.type"
            class="m-2"
            placeholder="Select"
            size="small"
            style="width: 100px;"
          >
            <el-option key="receiver" label="收件人" value="receiver" />
            <el-option key="sender" label="发件人" value="sender" />
            <el-option key="subject" label="主题" value="subject" />
          </el-select>
          
          <p style="margin: 0 4px;">包含</p>
          <el-input
            v-model="item.value"
            placeholder="请输入"
            size="small"
            style="width: 214px;"
          />
          <div class="btn-wrap">
            <el-button @click="addRuleItem" class="border mr2 plus-btn" size="samll">
              <i class="iconfont icon-plus" />
            </el-button>
            <el-button :disabled="ruleList.length === 1" class="border minus-btn"  size="samll">
              <i class="iconfont icon-minus" />
            </el-button>
          </div>
        </div>
      </div>
      <p class="bold tips mb8 mt20 font14">执行下列操作：</p>
      <div>
        <div class="flex-row mb10 rule-item-wrap">
          移动邮件
          <p style="margin: 0 4px;">到</p>
          <el-cascader
            v-model="folder"
            :options="options"
            :props="cascaderProps"
            size="small"
            style="width: 330px;"
          />
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button size="small" @click="closeRule">取消</el-button>
          <el-button size="small" type="primary" @click="saveRule">
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>
  </el-dialog>
</template>
<script lang="ts" setup>
  import { ref  } from 'vue';
  import { storeToRefs } from 'pinia';
  import { useEmail } from '/@/stores/email';
  import pinia from '/@/stores/index';
  import api from "/@/api/email/index"

  const ruleItemDialogVisible = ref(false);
  const ruleList = ref<any>([
    {
      type: 'receiver',
      value: ''
    }
  ]);
  const emailRuleList = ref<any>([])
  const currentRuleId = ref<string>('');
  const stores = useEmail(pinia);
  const { curAccount, accountList } = storeToRefs(stores);

  const folder = ref('')

  const cascaderProps = {
    expandTrigger: 'hover' as const,
    label: 'folderName',
    value: 'folderName',
    emitPath: false,
    checkStrictly: true 
  }
  const options = ref([]);
  const currentAccout = ref<any>(curAccount.value);
  const ediRule = () => {
    ruleList.value = [];
    const item = emailRuleList.value.find((i:any) => i.id === currentRuleId.value);
    let addresser = [];
    let recipients = [];
    let subject = [];
    if(item) {
      if(item.addresser) {
        // 发件人
        let addresserData = item.addresser.split(',');
        addresser = addresserData.map((i:any) => {
          return {
            type: 'sender',
            value: i
          }
        })
      }
      if(item.recipients) {
        // 收件人
        let recipientsData = item.recipients.split(',');
        recipients = recipientsData.map((i:any) => {
          return {
            type: 'receiver',
            value: i
          }
        })
      }
      if(item.theme) {
        // 收件人
        let subjectData = item.theme.split(',');
        subject = subjectData.map((i:any) => {
          return {
            type: 'subject',
            value: i
          }
        });
      }
      ruleList.value = [].concat(addresser, recipients, subject);
      folder.value = item.folder;
      ruleItemDialogVisible.value = true;
    }
  }

  const closeRule = () => {
    folder.value = '';
    ruleList.value = []
    ruleItemDialogVisible.value = false;
  };

  const saveRule = () => {
    let addresser:any = [];
    let recipients:any = [];
    let theme:any = []
    ruleList.value.forEach((i:any) => {
      if (i.type === 'receiver') {
        recipients.push(i.value);
      } else if(i.type === 'sender') {
        addresser.push(i.value);
      } else if(i.type === 'subject') {
        theme.push(i.value);
      }
    });
    const params: any = {
      account: currentAccout.value,
      addresser: addresser.join(),
      recipients: recipients.join(),
      theme: theme.join(),
      folder: folder.value,
      status: 0,
      isSeen: 0,
    };
    if(currentRuleId.value) {
      params.id = currentRuleId.value;
      api.rule.editItem(params).then((res: any) => {
        ruleItemDialogVisible.value = false;
        ruleList.value = [
          {
            type: 'receiver',
            value: ''
          }
        ]
        getList();
      });
    }else {
      api.rule.addItem(params).then((res: any) => {
        ruleItemDialogVisible.value = false;
        ruleList.value = [
          {
            type: 'receiver',
            value: ''
          }
        ]
        getList();
      });
    }
  }

  const formatCondition = (item: any) => {
    let str:any = ""
    // addresser 发件人
    // recipients 收件人
    // theme 主题
    if(item.addresser) {
      str += `发件人包含${item.addresser}、`
    }
    if(item.recipients) {
      str += `收件人包含${item.recipients}、`
    }
    if(item.theme) {
      str += `主题包含${item.theme}`
    }
    return str;
  }

  const formatOperation =  (item: any) => {
    return `移动到${item.folder}`
  }

  const changeEmailStatus = (i:any) => {
    api.rule.changeStatus({
      id: i.id,
      status: i.status
    }).then(() => {
      ElMessage.success('状态切换成功');
      getList();
    });
  }

  const addRuleItem = () => {
    ruleList.value.push({
      type: 'receiver',
      value: ''
    })
  }

  const addEmailItem = () => {
    ruleItemDialogVisible.value = true;
    currentRuleId.value = '';
  }

  /**
   * 删除邮箱
   */
  const deleteEmailItem = () => {
    ElMessageBox.confirm('此操作将删除该规则，是否继续？', '提示', {
      confirmButtonText: '清空',
      cancelButtonText: '取消',
    })
      .then(() => {
        api.rule.deleteItem(currentRuleId.value).then((res: any) => {
          ElMessage.success('删除成功');
          currentRuleId.value = '';
          getList();
        });
      })
      .catch(() => {

      });
    }

  const handleChangeStatus = (i: any) => {
    if(currentRuleId.value === i.id) {
      currentRuleId.value = '';
    }else {
      currentRuleId.value = i.id;
    }
  }

  const getFolderList = async () => {
    if (!currentAccout.value) {
      return;
    }
    api.folder.getList(currentAccout.value).then((res: any) => {
      options.value = res.data.filter((item: any) => {
        return ['星标邮件', '草稿箱'].indexOf(item.folderName) === -1;
      });
    });
  };

  const getList = async () => {
    api.rule.getList(currentAccout.value).then((res: any) => {
      emailRuleList.value = res.data;
    }); 
  };

  getFolderList();
  getList();
</script>
<style lang="scss" scoped>
.email-rule-dialog {
  .footer-wrap {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .email-rule-wrap {
    margin: 12px 0;
    border: 1px solid #dbdddd;
    height: 300px;
  }


}
.btn-wrap {
  margin-left: 8px;
  display: flex;
  .minus-btn {
    margin-left: 0px;
  }
  .plus-btn,
  .minus-btn {
    padding: 6px 8px;
    :deep(.el-icon) {
      margin-right: 0;
    }
    
  }

}

.el-input {
  height: 32px;
}
:v-deep .el-cascader {
  height: 32px;
  line-height: 32px;
  .el-input {
    --el-input-inner-height: 32px;
  }
}
:deep(.el-select__wrapper) {
  height: 32px;
}

.border {
  border: 1px solid #dbdddd;
}

.bold {
  font-weight: bold;
}

.tips {
  color: #000000;
}

.active {
  background: linear-gradient(#7d93a8, #6d7e8e);
  color: #fff;
}
.flex-row {
  padding: 2px 8px;
  .flex-row-item:nth-child(1) {
    width: 25px;
    text-align: center;
    
  }
  .flex-row-item:nth-child(2) {
    width: 275px;
    
  }
  .flex-row-item:nth-child(3) {
    width: 90px;
    
  }
}
.email-rule-table-head {
  border-bottom: 1px solid #dbdddd;
  background: #efefef;
}
</style>
<style lang="scss">
.email-rule-modal .el-dialog {
  padding-bottom: 20px;
}
</style>